package cz.muni.fi.pa165.dundd.serviceImpl;

import cz.muni.fi.pa165.dundd.assembler.Assembler;
import cz.muni.fi.pa165.dundd.dao.HeroDAO;
import cz.muni.fi.pa165.dundd.dao.TroopDAO;
import cz.muni.fi.pa165.dundd.dto.TroopDTO;
import cz.muni.fi.pa165.dundd.entity.Hero;
import cz.muni.fi.pa165.dundd.entity.Troop;
import cz.muni.fi.pa165.dundd.service.TroopService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Implementation of service layer functionality relevant to the Troop Entity.
 * Makes use of underlying DAO layer.
 * @author Šimon Demočko
 */
@Service
@Transactional
public class TroopServiceImpl implements TroopService {

    @Autowired
    private TroopDAO troopDAO;

    @Autowired
    private HeroDAO heroDAO;

    public void setTroopDAO(TroopDAO troopDAO) {
        this.troopDAO = troopDAO;
    }

    @Override
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    public void createTroop(TroopDTO troop) {
        troopDAO.createTroop(Assembler.troopDtoToEntity(troop));
    }

    @Override
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    public void updateTroop(TroopDTO troop) {
        troopDAO.updateTroop(Assembler.troopDtoToEntity(troop));
    }

    @Override
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    public void deleteTroop(TroopDTO troop) {      
        Troop troopEntity = Assembler.troopDtoToEntity(troop);
        for (Hero hero : heroDAO.retrieveAllHeroes()) {
            if ((hero.getMyParty() != null) && hero.getMyParty().equals(troopEntity)) {
                hero.setMyParty(null);
            }
        }
        troopDAO.deleteTroop(troopEntity);
    }

    @Override
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    public List<TroopDTO> retrieveAllTroops() {
        List<Troop> retrieveAllTroops = troopDAO.retrieveAllTroops();
        List<TroopDTO> result = new ArrayList<>();
        for (Troop troop : retrieveAllTroops) {
            result.add(Assembler.troopEntityToDTO(troop));
        }
        return result;  
    }

    @Override
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    public TroopDTO retrieveTroopById(Long id) {
        return Assembler.troopEntityToDTO(troopDAO.retrieveTroopById(id));
    }
}
